package com.pz.cloud.framework.stdGroup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pz.cloud.framework.base.dao.CommonDao;
import com.pz.cloud.framework.base.expection.CustomRuntimeException;
import com.pz.cloud.framework.base.service.BaseServiceImpl;
import com.pz.cloud.framework.business.society.entity.OrgSocietyUser;
import com.pz.cloud.framework.business.stdGroup.entity.OrgStdGroup;
import com.pz.cloud.framework.business.stdGroup.entity.OrgStdGroupUser;
import com.pz.cloud.framework.business.stdGroup.service.IOrgStdGroupService;
import com.pz.cloud.framework.business.stdGroup.service.IOrgStdGroupUserService;
import com.pz.cloud.framework.business.student.entity.Student;
import com.pz.cloud.framework.business.workflow.annotation.Workflow;
import com.pz.cloud.framework.business.workflow.enums.WorkflowEnum;
import com.pz.cloud.framework.model.AbstractSqlBuilder;
import com.pz.cloud.framework.model.SqlBuilder;
import com.pz.cloud.framework.stdGroup.callback.OrgStdGroupUserCallback;
import com.pz.cloud.framework.stdGroup.mapper.OrgStdGroupUserMapper;
import com.pz.cloud.framework.util.BizUtil;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.handler.DataScopeHandler;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class OrgStdGroupUserServiceImpl extends BaseServiceImpl<OrgStdGroupUserMapper, OrgStdGroupUser> implements IOrgStdGroupUserService {
    @Autowired
    private CommonDao commonDao;

    @Autowired
    private IOrgStdGroupService orgStdGroupService;

    @Autowired
    private ISysUserService sysUserService;

    @Workflow(callback = OrgStdGroupUserCallback.class)
    public boolean save(OrgStdGroupUser entity) {
        boolean flag ;
        if(StringUtils.isEmpty(entity.getId())){
            String stdGroupId = entity.getStdGroupId();
            if (StringUtils.isBlank(stdGroupId)) {
                String stdGroupName = entity.getStdGroupName();
                if (StringUtils.isBlank(stdGroupName)) {
                    throw new CustomRuntimeException("组织id和组织名称为空");
                }
                List<OrgStdGroup> stdGroups = orgStdGroupService.findByName(stdGroupName);
                if (CollectionUtils.isEmpty(stdGroups)) {
                    throw new CustomRuntimeException("该组织不存在");
                }
                stdGroupId = stdGroups.get(0).getId();
                entity.setStdGroupId(stdGroupId);
            }
            String userId = entity.getUserId();
            if (findByUserIdAndStdGroupId(userId, stdGroupId) != null) {
                throw new CustomRuntimeException("该用户申请中或已加入");
            }
            SysUser byId = sysUserService.getById(userId);
            if (byId == null) {
                throw new CustomRuntimeException("用户不存在");
            }
            entity.setRealname(byId.getRealname());
            flag = super.save(entity);
        }else{
            flag = super.updateById(entity);
        }
        OrgStdGroup orgStdGroup = orgStdGroupService.getById(entity.getStdGroupId());
        if (orgStdGroup != null) {
            entity.getWorkflowModel().setHandlerId(orgStdGroup.getDirectorId());
        }

        return flag;
    }

    @Override
    public IPage<OrgStdGroupUser> findPage(OrgStdGroupUser entity) {
        AbstractSqlBuilder sqlBuilder = sqlBuilder(entity);
        return commonDao.findPage(sqlBuilder);
    }

    @Override
    public IPage<OrgStdGroupUser> findApplyPage(OrgStdGroupUser entity) {
        AbstractSqlBuilder sqlBuilder = sqlBuilder(entity).append(" and ( gu.act_status in (").append(WorkflowEnum.ProcessStatus.流程中.getStatus().toString())
                .append(",").append(WorkflowEnum.ProcessStatus.流程退回.getStatus().toString()).append(") or (gu.act_status=").append(WorkflowEnum.ProcessStatus.未开启.getStatus().toString())
                .append(" and gu.user_id = :userId))").setParms("userId",BizUtil.getUserId());

        return commonDao.findPage(sqlBuilder);
    }

    @Override
    public OrgStdGroupUser findByUserIdAndStdGroupId(String userId, String stdGroupId) {
        LambdaQueryWrapper<OrgStdGroupUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrgStdGroupUser::getUserId,userId);
        queryWrapper.eq(OrgStdGroupUser::getStdGroupId,stdGroupId);
        return getOne(queryWrapper, false);

    }

    private AbstractSqlBuilder sqlBuilder(OrgStdGroupUser entity) {
        DataScopeHandler dataScopeHandler = new DataScopeHandler()
                .setOrgSql("g.id in (select std_group_id from org_std_group_user where user_id = :userId and del_flag = 0 )").setOrgParms("userId",BizUtil.getUserId())
                .setPersonalSql("gu.user_id = :userId ").setPersonalParms("userId",BizUtil.getUserId())
                 .setCustomSql(" or g.id in (SELECT" +
                " std_group_id FROM org_std_group_user" +
                " WHERE user_id = :userId and del_flag = 0 and is_director = 1" +
                ") ").setCustomParms("userId",BizUtil.getUserId());

        AbstractSqlBuilder sqlBuilder = SqlBuilder.init("select gu.*,g.director,g.name std_group_name,s.std_no,s.college,s.major,s.grade,s.clazz from ")
                .append(entity.getTableName()).append(" gu")
                .append(" inner join ").append(BizUtil.getTableName(OrgStdGroup.class)).append(" g on gu.std_group_id = g.id and g.del_flag = 0 ")
                .append(" left join ").appendTable(Student.class).append(" s on gu.user_id = s.user_id and s.del_flag = 0 ")
                .append(" where g.act_status >= 10")//正式成立的组织
                .returnType(OrgStdGroupUser.class)
                .page(entity)
                .joinCondition(entity, "gu")
                .filterDataScope(dataScopeHandler)
                .orderBy("gu.id desc");
        if(!StringUtils.isEmpty(entity.getStdGroupName())){
            sqlBuilder.append(" and g.name like :stdGroupName").setParmsLike("stdGroupName",entity.getStdGroupName());
        }
        return sqlBuilder;
    }

}
